echo_start "gdisk ${SD}"
cat << EOF | gdisk ${SD}
2
n


+1M
EF02
n


+${HD_NTFS_SIZE}M
0700
n


+128M
EF00
n




r
h
1 3 4
n

n

n

y
x
h
w
y
EOF
if [ $? -ne 0 ]; then
    echo_err "gdisk"
    exit 1
fi
echo_finish "gdisk ${SD}"

echo_start "mkfs $SD"
if ! {
    mkfs.ntfs -Q -F -L "DATA" ${SD}2 &&
    mkfs.vfat -F32 -n "EFI" ${SD}3 &&
    mkfs.btrfs -f -L "Arch Linux" ${SD}4
}; then
    echo_err "mkfs $SD"
    exit 1
fi
echo_finish "mkfs $SD"

echo_start "make files $SD"
if ! {
    mkdir -p $FS &&
    mkdir -p $ROOT &&
    mount ${SD}4 $FS -o noatime,autodefrag,compress=lzo
}; then
    echo_err "mount ${SD}4"
    exit 1
fi

if ! {
    mkdir -p $FS/snapshot
    mkdir -p $FS/active
    btrfs subvolume create $FS/active/ROOT
    btrfs subvolume create $FS/active/home
    btrfs subvolume create $FS/active/opt
    btrfs subvolume create $FS/active/var
}; then
    echo_err "btrfs subvolume create"
    exit 1
fi

if ! mount ${SD}4 $ROOT -o noatime,autodefrag,compress=lzo,subvol=active/ROOT; then
    echo_err "mount ROOT"
    exit 1
fi

if ! {
    mkdir -p $ROOT/home &&
    mkdir -p $ROOT/opt &&
    mkdir -p $ROOT/var/lib &&
    mount ${SD}4 $ROOT/home -o noatime,autodefrag,compress=lzo,subvol=active/home &&
    mount ${SD}4 $ROOT/opt -o noatime,autodefrag,compress=lzo,subvol=active/opt &&
    mount ${SD}4 $ROOT/var -o noatime,autodefrag,compress=lzo,subvol=active/var
}; then
    echo_err "mount"
    exit 1
fi

if ! {
    mkdir -p $ROOT/var/lib &&
    mount --bind $FS/active/ROOT/var/lib $ROOT/var/lib
}; then
    echo_err "mount bind"
    exit 1
fi


if ! {
    mkdir -p $ROOT/boot &&
    mkdir -p $ROOT/efi &&
    mount ${SD}3 $ROOT/efi
}; then
    echo_err "mount ${SD}3"
    exit 1
fi

if ! {
    mkdir -p $ROOT/data &&
    mount ${SD}2 $ROOT/data
}; then
    echo_err "mount ${SD}2"
    exit 1
fi

echo_finish "make files $SD"

# vim: ft=sh
